# encoding=utf-8
import uuid
import time
import datetime
import traceback

debug_print_prefix = '[qtlibs-dll-Debug]'
error_print_prefix = '[qtlibs-dll-Error]'


def build_order(symbol):
    fields = ['investunit_id', 'instance_id', 'iqe_symbol', 'entrust_direction', 'futures_direction', 'close_direction',
              'futu_invest_type', 'price_type', 'entrust_price', 'entrust_amount', 'ext_remark', 'module_id',
              'extsystem_id',

              'limit_ratio_future', 'limit_ratio_option', 'limit_entrust_ratio', 'strategy_req_id', 'strategy_flag_id',
              'capitalunit_id', 'market_no', 'stock_code']
    data = [
        [325, 428, symbol, 'BUY', 'OPEN', '', '1', 'A', 0, 100, 'cf49e3b6-613d-11eb-b455-dc1ba1d7c255', 9999, 0,
         0, 0, 0,
         0, 0, 0, '2', '000001']]
    # print('build entrust', dict(zip(fields, data[0])))
    return fields, data


def next_uuid():
    """
    获取ID
    :return:
    """
    return str(uuid.uuid1())


def next_id():
    """
    获取一个整数ID
    :return:
    """
    return int(time.time() * 100)


def next_time_id():
    n = str(datetime.datetime.now())
    return int(n[n.index('.'):].replace('.', ''))


def f(args):
    print(str(datetime.datetime.now()) + ' run f', args)
    time.sleep(2)


def test_scheduler():
    import schedule
    schedule.every(1).second.do(f, ("123",))
    while True:
        schedule.run_pending()
        time.sleep(1)


def format_exception(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            ne = traceback.format_exc()
            print(error_print_prefix + get_formative_exception(ne))

    return wrapper


def get_formative_exception(ne, feature='PythonScript'):
    ss = ne.split('\n')
    i = [i for i, s in enumerate(ss) if feature in s]
    i = i[0] if i else -4
    ss = ss[i:]
    ne = 'NEWLINE'.join(ss)
    return ne


# 早上9点半时间
def get_morning_nine_half_clock():
    now = datetime.datetime.now()
    year = now.year
    month = now.month
    day = now.day
    hour = 9
    minute = 30
    second = 0
    return datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)


# 下午15点时间
def get_afternoon_fifteen_clock():
    now = datetime.datetime.now()
    year = now.year
    month = now.month
    day = now.day
    hour = 15
    minute = 0
    second = 0
    return datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)


# 中间休市时间
def get_stock_sleep_time():
    now = datetime.datetime.now()
    year = now.year
    month = now.month
    day = now.day
    hour_a = 11
    minute_a = 31
    second_a = 0
    a_end = datetime.datetime(year=year, month=month, day=day, hour=hour_a, minute=minute_a, second=second_a)

    hour_p = 13
    minute_p = 0
    second_p = 0
    p_start = datetime.datetime(year=year, month=month, day=day, hour=hour_p, minute=minute_p, second=second_p)

    if a_end < now < p_start:
        return True

    return False


def get_minute_time(int_datetime):
    """
    整型时间换datetime时间格式
    :param int_datetime:
    :return:
    """
    if len(str(int_datetime)) != 14:
        raise Exception('请输入14位整型时间格式！')
    year = int(str(int_datetime)[:4])
    month = int(str(int_datetime)[4:6])
    day = int(str(int_datetime)[6:8])
    hour_a = int(str(int_datetime)[8:10])
    minute_a = int(str(int_datetime)[10:12])
    second_a = 0
    return datetime.datetime(year=year, month=month, day=day, hour=hour_a, minute=minute_a, second=second_a)


# 市场类型分类
stock_market_no = ['XSHG', 'XSHE']
neeq_market_no = ['NEEQ']
future_market_no = ['XSGE', 'XZCE', 'CCFX', 'XDCE']
option_market_no = ['XSHO', 'XSZO', 'XSGE-O', 'XZCE-O', 'CCFX-O', 'XDCE-O']
future_option_market_no = ['XSGE', 'XZCE', 'CCFX', 'XDCE', 'XSGE-O', 'XZCE-O', 'CCFX-O', 'XDCE-O']
stock_option_market_no = ['XSHG', 'XSHE', 'XSHO', 'XSZO']
import six


def get_code_asset(security):
    if isinstance(security, six.string_types):
        exchange = security.split('.')[1]
        if exchange in stock_market_no:
            if security in stock_asset_dict.keys():
                asset = stock_asset_dict[security]
            else:
                asset = etf_asset_dict[security]
        elif exchange in future_market_no:
            asset = future_asset_dict[security]
        elif exchange in option_market_no:
            asset = option_asset_dict[security]
        elif exchange in neeq_market_no:
            asset = stock_asset_dict[security]
        else:
            asset = None
    else:
        key = security.symbol
        if security.exchange in stock_market_no:
            if key in stock_asset_dict.keys():
                asset = stock_asset_dict[key]
            else:
                asset = etf_asset_dict[key]
        elif security.exchange in future_market_no:
            asset = future_asset_dict[key]
        elif security.exchange in option_market_no:
            asset = option_asset_dict[key]
        elif security.exchange in neeq_market_no:
            asset = stock_asset_dict[key]
        else:
            asset = None
    return asset


if __name__ == '__main__':
    a = next_uuid()
    try:
        print(1 / 0)
    except Exception as e:
        ne = traceback.format_exc()
        get_formative_exception(ne)
    # test_scheduler()
